$(function () {
  window.parent.cateid = ''
  const layer = layui.layer
  const laydate = layui.laydate
  const laypage = layui.laypage
  laydate.render({
    elem: '#test',
    type: 'datetime',
    range: true,
    change: function (value, date, endDate) {
      value = value.replace(/\s+(-)\s+/, ',')
      const arr = value.split(',')
      art_query.start_time = new Date(arr[0]).getTime()
      art_query.end_time = new Date(arr[1]).getTime()
    }
  })
  // 获取所有分类数据
  async function getCate() {
    const { data: res } = await axios({
      method: 'GET',
      url: '/ydd_cate/all'
    })
    if (res.errno !== 0) {
      return layer.msg('获取分类列表数据失败！')
    }
    const cateStr = res.data
      .map(item => {
        return `<option value="${item.id}">${item.catename}</option>`
      })
      .join('')
    $('[name=cateid]').html('<option value=""></option>' + cateStr)
  }
  getCate()
  // 获取文章列表数据
  let art_query = {
    cateid: '',
    title: '',
    start_time: '',
    end_time: '',
    page: '1',
    limit: '10'
  }
  async function getArtList(q) {
    const index = layer.load(0, {
      shade: [0.7, '#fff']
    })
    const { data: res } = await axios({
      method: 'GET',
      url: '/ydd_article/list',
      params: q
    })
    if (res.errno !== 0) {
      return layer.msg('获取图书列表失败！')
    }
    // console.log(res)
    layer.close(index)
    renderTable(res.data.data)
    renderPage(res.data.count)
  }
  function renderTable(data) {
    const htmlStr = data
      .map(item => {
        return `<tr>
      <td>${item.id}</td>
      <td>${item.title}</td>
      <td>${item.catename || ''}</td>
      <td>
      <span style="display:none">${item.pic}</span>
        <img src="http://124.223.14.236:8060/${resolveImg(item.pic)}" alt="">
      </td>
      <td>${formatDate(item.create_date)}</td>
      <td>
        <span style="display:none">${item.ishot}</span>
        <form class="layui-form"><input type="checkbox" lay-skin="switch" ${item.ishot === 1 ? 'checked' : ''} disabled /></form>
      </td>
      <td>
        <span style="display:none">${item.istop}</span>
        <form class="layui-form"><input type="checkbox" lay-skin="switch" ${item.istop === 1 ? 'checked' : ''} disabled /></form>
      </td>
      <td><span class="el-tag">${artStatus(item.status)}</span></td>
      <td data-id="${item.id}">
        <button type="button" class="layui-btn layui-btn-normal layui-btn-xs layui-btn-radius btnEdit"><i class="layui-icon layui-icon-edit"></i></button>
        <button type="button" class="layui-btn layui-btn-danger layui-btn-xs layui-btn-radius btnDelete"><i class="layui-icon layui-icon-delete"></i></button>
      </td>
      </tr>`
      })
      .join('')
    $('tbody').html(htmlStr)
    // layui 开关按钮在获取数据渲染后需要重新调用layui.js才能渲染出来  因此需要再次引入
    $('#layui-script').remove()
    $('body').append('<script src="./lib/layui/layui.all.js"  id="layui-script"></script>')
  }
  getArtList(art_query)
  // 文章状态
  function artStatus(status) {
    switch (status) {
      case 0:
        return '待审核'
      case 1:
        return '草稿箱'
      case 2:
        return '已发布'
      case 3:
        return '已删除'
      default:
        return ''
    }
  }
  // 时间格式化
  function formatDate(date) {
    const dt = new Date(date)
    let y = dt.getFullYear()
    let m = dt.getMonth() + 1
    m = m < 10 ? '0' + m : m
    let d = dt.getDate()
    d = d < 10 ? '0' + d : d
    return `${y}-${m}-${d}`
  }
  // 处理图片函数
  function resolveImg(imgStr) {
    if (!imgStr) {
      return ''
    }
    const arr = imgStr.split(',')
    return arr[0]
  }
  // 分页器初始化
  function renderPage(total) {
    laypage.render({
      elem: 'page-box',
      count: total,
      limit: art_query.limit,
      curr: art_query.page,
      limits: [10, 20, 40, 50, 100],
      theme: '#409eff',
      layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
      jump: function (obj, first) {
        art_query.page = obj.curr
        art_query.limit = obj.limit
        if (!first) {
          // console.log(art_query)
          getArtList(art_query)
        }
      }
    })
  }
  // 搜索提交数据
  $('#form-search').on('submit', function (e) {
    e.preventDefault()
    const cateid = $('.select-cate .layui-this').attr('lay-value')
    art_query.cateid = cateid || ''
    const title = $('[name=title]').val()
    art_query.title = title
    getArtList(art_query)
    // $(this)[0].reset()
  })
  // 给重置按钮绑定事件
  $('.btnReset').on('click', function () {
    art_query.title = ''
    art_query.cateid = ''
    art_query.start_time = ''
    art_query.end_time = ''
    getArtList(art_query)
  })
  // 删除文章按钮事件
  $('tbody').on('click', '.btnDelete', function () {
    const id = $(this).parent().attr('data-id')
    const len = $('.btnDelete').length
    layer.confirm('确定要删除吗?', { icon: 3, title: '提示' }, async function (index) {
      //do something
      const { data: res } = await axios({
        method: 'GET',
        url: '/ydd_article/del',
        params: {
          id
        }
      })
      if (res.errno !== 0) {
        return layer.msg('删除文章失败！')
      }
      layer.msg('删除文章成功！')
      if (len === 1) {
        art_query.page--
      }
      getArtList(art_query)
      layer.close(index)
    })
  })
  // 点击按钮隐藏搜索栏
  $('.hide-serarch').on('click', function () {
    $('.layui-card-header').slideToggle()
    $(this).find('i').toggleClass('layui-icon-up')
  })
  // 点击按钮刷新页面
  $('.refresh').on('click', function () {
    $('.x-nav a').click()
  })
  // 点击新增按钮跳转到add_article页面
  $('.btn-add').on('click', function () {
    const iframe = window.parent.document.querySelector('.layui-show .x-iframe')
    iframe.src = './add_article.html'
  })
  // 点击编辑按钮跳转到add_article页面并且将获得的cateid传入
  $('tbody').on('click', '.btnEdit', function () {
    const id = $(this).parent().attr('data-id')
    window.parent.cateid = id
    window.parent.document.querySelector('.layui-show .x-iframe').src = './add_article.html'
  })
  // 导出数据为excel表格
  // 引入 SheetJS 库 调用方法实现
  function ExportToExcel(type, fn, dl) {
    var elt = document.getElementById('table')
    var wb = XLSX.utils.table_to_book(elt, { sheet: 'sheet1' })
    return dl ? XLSX.write(wb, { bookType: type, bookSST: true, type: 'base64' }) : XLSX.writeFile(wb, fn || 'ArtList.' + (type || 'xlsx'))
  }
  $('.btn-download').on('click', function () {
    ExportToExcel()
  })
  // 渲染出隐藏整列的选项
  renderIptHide()
  function renderIptHide() {
    let arr = []
    $('thead th').each(function (i, item) {
      arr.push(`<div class="layui-form-item">
      <input type="checkbox" value="${$(item).html()}" title="${$(item).html()}" lay-skin="primary" checked />
      </div>`)
    })
    $('#form-hideCol').html(arr.join(''))
  }
  // 隐藏整列功能
  $('#btn-hide').on('click', function () {
    $('.ipt-box').slideToggle()
  })
  $('.ipt-box').on('click', '.layui-form-checkbox', function () {
    const index = $(this).parent().index()
    const status = $(this).attr('class').includes('layui-form-checked')
    if (status) {
      $('table colgroup').eq(index).removeClass('layui-hide')
      $('thead tr th').eq(index).removeClass('layui-hide')
      $('tbody tr').each(function (i, item) {
        $(item).find('td').eq(index).removeClass('layui-hide')
      })
    } else {
      $('table colgroup').eq(index).addClass('layui-hide')
      $('thead tr th').eq(index).addClass('layui-hide')
      $('tbody tr').each(function (i, item) {
        $(item).find('td').eq(index).addClass('layui-hide')
      })
    }
  })
})
